package com.demo.activityservicedemo.demo2

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.os.Message
import android.os.Messenger
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import com.demo.activityservicedemo.R

/**
 * Created by zhangyuncai on 2024/6/27.
 * Messenger是一个基于消息的IPC（进程间通讯）机制，适用于Activity与Service之间的一对一通讯。
 */
class Demo2Activity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_demo2)

        val intent = Intent(this, Demo2Service::class.java)
        bindService(intent, connection, Context.BIND_AUTO_CREATE)

        findViewById<Button>(R.id.bt_demo2_sendtoservice)
            .setOnClickListener {
                val message = Message()
                val bundle = Bundle()
                bundle.putString("test", "haah")
                message.data = bundle
                messenger?.send(message)
            }
    }

    var messenger: Messenger? = null

    var connection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            messenger = Messenger(service)
        }

        override fun onServiceDisconnected(name: ComponentName?) {
        }

    }

    override fun onDestroy() {
        unbindService(connection)
        super.onDestroy()
    }
}